/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-12-09
 * Time: 23:48
 */

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public void flatten(TreeNode root) {
        TreeNode cur=root;
        while(cur!=null){
            if(cur.left!=null){
                //有左子树,找到最右边的节点,让其指向当前节点的下一个节点
                TreeNode rightest=cur.left;
                while(rightest.right!=null){
                    rightest=rightest.right;
                }
                //注意这里最右边的节点指向了当前节点的右节点,而不是指向当前节点
                rightest.right=cur.right;
                //修改当前节点的指针
                //当前节点右指针指向左孩子,左指针指向空
                cur.right=cur.left;
                cur.left=null;
            }
            //因为前面已经修改过指针,所以都是移动到当前节点的右孩子
            cur=cur.right;
        }
    }
}
